/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.zavakid.scala.exercise.chapter2

/**
 * @author zavakid 2013-6-7 下午4:41:11
 * @since 1.0
 */
object Main2 extends App {
  //1
  def no1(x: Int) = {
    if (x > 0) 1 else if (x < 0) -1 else 0
  }

  //2 () Unit

  //3
  // var x: Unit
  // var y: Int
  // then x = y =1 is legal

  //4
  def no4() {
    for (i <- 10 to 1 by -1) {
      println(i)
    }
  }
  //no4()
  def no4_2() {
    for (i <- new Range(10, 0, -1)) yield {
      println(i)
    }
  }
  //no4_2()

  //5
  def countdown(n: Int) {
    for (i <- n to 1 by -1) {
      println(i)
    }
  }
  //countdown(9)

  //6
  def no6(str: String): Long = {
    var result: Long = 1
    for (c <- str) {
      result *= c.toInt
    }
    result
  }

  //7
  def no7(str: String): Long = {
    var result: Long = 1
    str.foreach(result *= _.toInt);
    result
  }

  //8
  def product: String => Long = no7

  //9
  def no9(str: String): Long = {
    def no9_recursion(strTail: String, acc: Long): Long = {
      if (strTail.isEmpty) acc else no9_recursion(strTail.tail, acc * strTail.head.toInt)
    }
    no9_recursion(str, 1)
  }

  def no10(x: Int, n: Int): Int = {
    if (n == 0) 1
    else if (n < 0) 1 / no10(x, -n)
    else if (n % 2 == 0) no10(x, n / 2) * no10(x, n / 2)
    else x * no10(x, n - 1)
  }

  println(no10(5, -1))

}